package com.yuan.util.net;

import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.IOException;
import java.util.Properties;

/**
 * 邮件发送工具
 * @author YouYuan
 * @version 1.0
 * @CreateDate 2018/7/10 15:32
 * @UpdateDate 2018/7/10 15:32
 */
public class Mail {

    private Properties mailServerConfig = new Properties();// 邮件服务器配置
    private Authenticator mailUserInfo;// 邮件账号信息
    private MimeMessage msg;
    private static final String MAIL_FORMAT = "text/html;charset=utf-8";
    private Properties mailInfo = new Properties();// 邮件信息
    private MimeMultipart list;// 多部分邮件主体（支持附件）
    private File[] files;//文件附件

    /**
     * 设置邮件服务器参数
     *
     * @param mailHost
     *            主机地址
     * @param auth
     *            是否需要验证（true/false）
     */
    public void setMailServerConfig(String mailHost, String auth) {
        mailServerConfig.setProperty("mail.host", mailHost);
        mailServerConfig.setProperty("mail.smtp.auth", auth);
    }

    /**
     * 设置邮件服务器
     *
     * @param mailHost
     */
    public void setMailHost(String mailHost) {
        mailServerConfig.setProperty("mail.host", mailHost);
        mailServerConfig.setProperty("mail.smtp.auth", "true");
    }

    /**
     * 设置用户信息
     *
     * @param username
     *            用户名
     * @param password
     *            密码
     */
    public void setMailUserInfo(final String username, final String password) {
        mailUserInfo = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        };
        mailInfo.setProperty("from", username);
    }

    /**
     * 初始化邮件服务
     */
    private void initializeMailServer() {
        Session session = Session.getDefaultInstance(mailServerConfig, mailUserInfo);
        msg = new MimeMessage(session);
        list = new MimeMultipart();
    }

    /**
     * 设置发件人
     *
     * @param address
     */
    public void setMailFrom(String address) {
        mailInfo.setProperty("from", address);
    }

    /**
     * 设置收件人
     *
     * @param address
     */
    public void setMailTO(String address) {
        mailInfo.setProperty("to", address);
    }

    /**
     * 设置抄送人
     *
     * @param address
     */
    public void setMailCC(String address) {
        mailInfo.setProperty("cc", address);
    }

    /**
     * 设置暗送人
     *
     * @param address
     */
    public void setMailBCC(String address) {
        mailInfo.setProperty("bcc", address);
    }

    /**
     * 设置附件
     * @param files
     */
    public void setFiles(File...files) {
        this.files = files;
    }

    /**
     * 设置邮件主题
     *
     * @param subject
     */
    public void setSubject(String subject) {
        mailInfo.setProperty("subject", subject);
    }

    /**
     * 设置邮件正文
     *
     * @param content
     */
    public void setMailContent(String content) {
        mailInfo.setProperty("content", content);
    }

    /**
     * 发送邮件
     *
     * @throws MessagingException
     */
    public void send() throws MessagingException {
        initializeMailServer();
        writeMail();
        Transport.send(msg);
    }

    /**
     * 写邮件（组装数据）
     * @throws MessagingException
     * @throws AddressException
     */
    private void writeMail() {
        // 添加发件信息
        String from = mailInfo.getProperty("from");
        String to = mailInfo.getProperty("to");
        String cc = mailInfo.getProperty("cc");
        String bcc = mailInfo.getProperty("bcc");
        String subject = mailInfo.getProperty("subject");
        String content = mailInfo.getProperty("content");
        MimeBodyPart contentPart = new MimeBodyPart();
        try {
            if (from != null) {
                msg.setFrom(new InternetAddress(from));
            } else {
                throw new RuntimeException("发件人不能为空");
            }
            if (to != null) {
                msg.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(to));
            } else {
                throw new RuntimeException("收件人不能为空");
            }
            if (cc != null) {
                msg.setRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(cc));
            }
            if (bcc != null) {
                msg.setRecipients(MimeMessage.RecipientType.BCC, InternetAddress.parse(bcc));
            }
            if (subject != null) {
                msg.setSubject(subject);
            }
            if (content != null) {
                contentPart.setContent(content, MAIL_FORMAT);
                list.addBodyPart(contentPart);// 添加邮件正文
            } else {
                throw new RuntimeException("邮件内容不能为空");
            }
            // 添加附件
            if (files != null) {
                for (File file : files) {
                    MimeBodyPart filePart = new MimeBodyPart();
                    try {
                        filePart.attachFile(file);// 设置附件内容
                        filePart.setFileName(MimeUtility.encodeText(file.getName()));// 设置附件显示的文件名称，编码解决中文乱码问题
                        list.addBodyPart(filePart);// 添加到邮件主体
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            msg.setContent(list);// 将邮件主体添加给message
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

}
